/**
 * 
 */
package com.sesame.serviceimpl;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;

import com.sesame.dao.UserDAO;
import com.sesame.domain.User;
import com.sesame.service.UserService;

/**
 * @author shubeta
 *
 */
public class UserServiceImpl implements UserService {
	
    private UserDAO userDAO;
    
    public void setUserDAO(UserDAO userDAO){
        this.userDAO = userDAO;
    }

    public boolean register(User user, Map model) {
        User emailUser = userDAO.getUserByEmail(user.getEmail());
        User nickNameUser = userDAO.getUserByNickName(user.getNickName());
        
        if (emailUser == null && nickNameUser == null) {
            userDAO.addUser(user);
            return true;

        } 
        else 
        {
            if (emailUser != null) {
                model.put("error_email", "该邮箱已被注册！");
            }
            if (nickNameUser != null) {
                model.put("error_nickName", "该昵称已被使用！");
            }
            return false;
        }
    }
    
    public boolean validatePassword(User user, String confirmPassword, Map model) {
        if (confirmPassword.equals(user.getPassword())) {
            return true;
        }
        else {
            model.put("error_password", "两次密码输入不一致！");
            return false;
        }
    }

    public boolean validateCode(HttpServletRequest request,
            String identifyCode, Map model) {
        String rand = (String) request.getSession().getAttribute("rand");
        if (identifyCode.equals(rand)) {
            return true;
        }
        else {
            model.put("error_identifyCode", "验证码错误！");
            return false;
        }
    }

    public boolean login(User user, Map model) {
        User dbUser = userDAO.getUserByEmail(user.getEmail());
        if (dbUser == null || !dbUser.getPassword().equals(user.getPassword())) {
            model.put("error_user", "该用户不存在或密码错误！");
            return false;
        } 
        else {
            userDAO.updateUser(user);
            return true;
        }
    }
	
	public boolean findPassword(User user, Map model) {
	    User dbUser = userDAO.getUserByEmail(user.getEmail());
	    if (dbUser != null){
	        /* send an email to the user */
	        return true;
	    }
	    else {
	        model.put("error_email", "该邮箱不存在！");
	        return false;
	    }
	}

}
